// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

async function addUser(userid, username, avatar) {
  const dateTime = new Date();
  return await db.collection('tb_user_info').add({
    data: {
      _id: userid,
      username: username,
      password: '',
      real_name: '',
      gender: 0,
      avatar: avatar,
      phone: '',
      user_state: 1,
      role_id: 3,
      created_time: dateTime,
      modified_time: dateTime,
      login_time: dateTime,
    }
  });
}

function checkUser(userid) {
  return new Promise(resolve => {
    db.collection('tb_user_info')
      .where({ _id: userid }).count()
      .then(res => resolve(res.total));
  })
}

async function updateUserLoginTime(userid) {
  const dateTime = new Date();
  return await db.collection('tb_user_info')
    .where({ _id: userid })
    .update({
      data: {
        login_time: dateTime
      },
    })
}

async function getUserInfo(userid) {
  let res = await db.collection('tb_user_info').aggregate()
    .match({ _id: userid })
    .lookup({
      from: 'tb_role_info',
      localField: 'role_id',
      foreignField: '_id',
      as: 'role'
    })
    .project({
      username: 1, real_name: 1, gender: 1, avatar: 1, phone: 1, role_id: 1,
      role_name: $.arrayElemAt(['$role.role_name', 0]), user_state: 1,
    })
    .end();
  return res.list[0];
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  let userExist = await checkUser(openid);
  let errMsg = '';
  if (!userExist && event.username && event.avatar) {
    try {
      await addUser(openid, event.username, event.avatar);
      userExist = 1;
    } catch (error) {
      errMsg = error
    }
  }
  let userInfo = null;
  if (userExist) {
    await updateUserLoginTime(openid);
    userInfo = await getUserInfo(openid);
    if (userInfo.user_state == 0) {
      errMsg = '用户被禁用，请联系管理员';
      userInfo = null;
    }
  }
  return { userExist, errMsg, userInfo };
}